import {Component, EventEmitter, Input, OnInit, Output} from "@angular/core";
import {CustomTimeRender} from "../../utils/CustomTimeRender";
import {DataDataSource} from "./cost-list.component";
import {BillExtaService} from "../../energy/api/api/billExta.service";
import {ViewCell} from "ng2-smart-table";
import {BaseRequest} from "../../utils/BaseRequest";
import {forkJoin} from "rxjs";
import {NbDialogRef} from "@nebular/theme";


@Component({
  templateUrl: './rate-bind.component.html'
})
export class RateBindComponent implements OnInit {
  @Input("data") data: { unitId: number, unitName: string };
  settings = {
    pager: {
      display: true,
      perPage: 5,
    },
    hideSubHeader: true,
    actions: {
      add: false,
      edit: false,
      delete: false,
      columnTitle: '操作',
      position: 'right',
    },
    columns: {
      name: {
        title: '名称',
        type: 'string',
      },
      startTime: {
        title: '起始时间',
        type: 'custom',
        renderComponent: CustomTimeRender
      },
      endTime: {
        title: '结束时间',
        type: 'custom',
        renderComponent: CustomTimeRender
      },
      rate: {
        title: '费率',
        type: 'string',
      },
      extInfo: {
        title: '备注',
        type: 'string',
      },
      add: {
        title: '操作',
        type: 'custom',
        renderComponent: RateBindActionRender,
        onComponentInitFunction: (instance) => {
          instance.save.subscribe(result => {
            this.selectedItems.push(result);
          })
        }
      }
    },
  };
  source: DataDataSource;
  selectedItems: { id: number, name: string, startTime: string, endTime: string, rate: number, extInfo: string }[] = [];

  constructor(private api: BillExtaService,protected ref: NbDialogRef<RateBindComponent>) {

  }

  ngOnInit(): void {
    this.source = new DataDataSource(this.api);
  }

  save() {
    forkJoin(this.selectedItems.map(value =>
      this.api.postBindECARate(new BaseRequest({
        operation: 0,
        rateId: value.id,
        unitId: this.data.unitId
      }))
    )).subscribe(resuls => {
      this.ref.close();
    })
  }
}

@Component({
  template: `
      <button nbButton (click)="add()" size="small" status="info">添加</button>`
})
export class RateBindActionRender implements OnInit, ViewCell {
  @Input() rowData: any;
  @Input() value: string | number;
  @Output() save: EventEmitter<any> = new EventEmitter();

  ngOnInit(): void {
  }

  add() {
    this.save.emit(this.rowData);
  }

}
